import { Suggestion, searchResult } from "@/types/data";
import { SearchAction } from "@/types/store";
type SearchState = {
  suggestion: Suggestion["options"];
  searchResults: searchResult;
};
const initialState: SearchState = {
  suggestion: [],
  searchResults: {
    page: 0,
    per_page: 0,
    total_count: 0,
    results: [],
  },
};
const Search = (state = initialState, action: SearchAction): SearchState => {


  switch (action.type as string) {
    case "search/suggestion":
      // 在这里对 action.payload 进行类型检查和转换
      const payloadOptions = Array.isArray(action.payload)
        ? action.payload
        : [];
      return {
        ...state,
        suggestion: payloadOptions,
      };
    case "search/clearSuggestion":
      return {
        ...state,
        suggestion: [],
      };
    case "search/getSearchResult":
      // 使用类型守卫来检查 action.payload 是否为 searchResult 类型
      if ("results" in action.payload) {
        return {
          ...state,
          searchResults: action.payload as searchResult,
        };
      } else {
        // 如果不是 searchResult 类型，则返回初始状态中的 searchResults
        return {
          ...state,
          searchResults: initialState.searchResults,
        };
      }
    default:
      return state;
  }
};
export default Search;
